#!/usr/bin/python
"""Build javascript packages used in Minerva.

Assumes running from mnerv/script dir.
"""

from os import path
import StringIO
import sys
MNERV_ROOT = path.split(path.dirname(path.abspath(__file__)))[0]
sys.path.insert(0, MNERV_ROOT)

import yaml as pyyaml

from third_party.py import jsmin
from third_party import javascript as third_party_javascript
import javascript

SITE_CONFIG = pyyaml.load(open(path.join(MNERV_ROOT, 'site.yaml')))
TARGET_EXT = 'min%d.js' % SITE_CONFIG['js_build']
BUILD_YAML = 'build.yaml'


def ProcessJsDir(dirpath):
  print "Processing:", dirpath
  build_path = path.join(dirpath, BUILD_YAML)
  build_config = pyyaml.load(open(build_path))
  for target_id, source_filenames in build_config.iteritems():
    print "\tMaking target:", target_id
    ins = StringIO.StringIO()
    # Concat them all
    for filename in source_filenames:
      print "\t\tConcat'ing:", filename
      other_dirpath, filename = path.split(filename)
      source = open(path.join(other_dirpath or dirpath, filename))
      ins.write(source.read())
      ins.write(';')
      source.close()

    # Then minify the result, writing to target
    ins.seek(0)
    target_path = path.join(dirpath, '%s.%s' % (target_id, TARGET_EXT))
    target = open(target_path, 'w')
    print "\t\tMinifying and writing:", target_path
    jsmin.JavascriptMinify().minify(ins, target)
    print "\t\tDone."
 

def main():
  third_party_path = third_party_javascript.__path__[0]
  ProcessJsDir(third_party_path)
  app_path = javascript.__path__[0]
  ProcessJsDir(app_path)
     

if __name__ == '__main__':
  main()
